package richbar.com.richbar.view.dialog;

import android.app.Activity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

import richbar.com.richbar.R;


/**
 * Created by qyang on 2017-10-27.
 */

public class SingleSelectDialog {
    private Activity mActivity;
    private String select;
    private int which = -1;
    private OnSelectListener listener;
    private android.support.v7.app.AlertDialog dialog;

    public SingleSelectDialog(Activity mActivity) {
        this.mActivity = mActivity;
    }

    public void showSingleDialog(String title,List<String> contents,OnSelectListener listener){
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(mActivity);
        View view = View.inflate(mActivity, R.layout.dialog_select, null);
        builder.setView(view);
        builder.setCancelable(true);
        TextView titleTv = view.findViewById(R.id.title);
        titleTv.setText(title);
        RecyclerView recyclerView = view.findViewById(R.id.recycleview);
        MAdapter adapter = new MAdapter(R.layout.item_single_select,contents,listener);
        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        dialog = builder.create();
        dialog.show();
    }


    class MAdapter extends BaseQuickAdapter<String> {
        OnSelectListener listener;
        public MAdapter(int layoutResId, List<String> data,OnSelectListener listener) {
            super(layoutResId, data);
            this.listener = listener;
        }

        @Override
        protected void convert(final BaseViewHolder holder, final String s) {
            holder.setText(R.id.content,s);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    which = holder.getAdapterPosition();
                    notifyDataSetChanged();
                    select = s;
                    if (which >= 0){
                        listener.onSelect(s,which);
                        dialog.dismiss();
                    }
                }
            });
        }
    }


    public interface OnSelectListener{
        void onSelect(String s, int pos);
    }
}
